package com.lifq.tmp;

import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.io.IOUtils;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;


public class ApiRequestDemoFile {

    private static OkHttpClient client = new OkHttpClient();
    //private static String apiHost = "http://10.0.113.62:29993";
    private static String apiHost = "http://localhost:8080";
    //private static String apiHost = "http://s23001411501.dev.internal.virtueit.net:82/v3-release/sybddataapi";
    private static String appkey = "test001";
    private static String secret = "b3d25076-9276-4cae-ae20-d25e6f8f7296";

    public static void main(String[] args) throws Exception {
        String path = "/wj0613test";
        String method = "GET";
        Map<String, List<String>> queryParams = new HashMap<>();
        // queryParams.put("aa", Arrays.asList("123"));
        // queryParams.put("bb", Arrays.asList("789"));

        Long timestamp = System.currentTimeMillis();
        String sign = sign(queryParams, timestamp);

        executeRequest(method, path, queryParams, timestamp, sign);

    }

    private static String sign(Map<String, List<String>> queryParams, Long timestamp) {
        StringBuilder signStr = new StringBuilder(appkey).append(timestamp);

        TreeMap<String, List<String>> sortParams = new TreeMap<>(queryParams);
        for (String key : sortParams.keySet()) {
            List<String> values = sortParams.get(key);
            if (values == null) {
                //空参数不参与校验
                continue;
            }
            String valueStr = values.stream().sorted(String.CASE_INSENSITIVE_ORDER).collect(Collectors.joining(","));
            if ("".equals(valueStr.trim())) {
                //空参数不参与校验
                continue;
            }
            signStr.append("&").append(key).append("=").append(valueStr);
        }

        String sign = sign(signStr.toString());
        return sign;
    }


    private static String sign(String signStr) {
        byte[] bytes = null;
        try {
            SecretKey secretKey = new SecretKeySpec(secret.getBytes("utf-8"), "HmacMD5");
            Mac mac = Mac.getInstance(secretKey.getAlgorithm());
            mac.init(secretKey);
            bytes = mac.doFinal(signStr.getBytes("utf-8"));
        } catch (Exception gse) {
            throw new RuntimeException(gse);
        }
        return byte2hex(bytes);
    }

    private static String byte2hex(byte[] bytes) {
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1) {
                str.append("0");
            }
            str.append(hex.toUpperCase());
        }
        return str.toString();
    }

    private static String executeRequest(String method, String path, Map<String, List<String>> queryParams, Long timestamp, String sign) throws IOException {
        URL url = new URL(apiHost);
        HttpUrl.Builder urlBuilder = new HttpUrl.Builder().scheme(url.getProtocol()).host(url.getHost()).port(url.getPort()).encodedPath(path);
        for (String key : queryParams.keySet()) {
            List<String> values = queryParams.get(key);
            for (String value : values) {
                urlBuilder.addQueryParameter(key, value);
            }
        }

        Request.Builder requestBuilder = new Request.Builder().method(method, null).url(urlBuilder.build())
                .addHeader("x-data365-appkey", appkey)
                .addHeader("x-data365-timestamp", timestamp.toString())
                .addHeader("x-data365-sign", sign)
                .addHeader("remoteFilePath", "/sy_cmsr/wjtest/tt.pdf")
                .addHeader("teamId", "1386571776264052738");
        Response response = client.newCall(requestBuilder.build()).execute();
        System.out.println(response.code());
        File file = new File("out3.pdf");
        if (!file.exists()) {
            file.createNewFile();
        }

        try(InputStream inputStream = response.body().byteStream();
            FileOutputStream fos = new FileOutputStream(file)) {
            System.out.println(inputStream.available());
            IOUtils.copy(inputStream, fos);
        }catch (Exception e){
            e.printStackTrace();
        }

        System.out.println("写入文件成功");

        return null;
    }
}
